package com.aaa.sso.service;

import com.aaa.common.bo.User;
import com.aaa.common.constants.ExceptionConstant;
import com.aaa.common.constants.ReturnCode;
import com.aaa.common.util.Result;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import java.util.concurrent.TimeUnit;

/**
 * @fileName:UserServiceImpl
 * @description:
 * @author:忆尘
 * @createTime:2020/11/13 16:16
 * @version:1.0.0
 */
@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private RedisTemplate redisTemplate;

    @Override
    public Result userLogin(String userName, String passWord) {
        // 收集用户信息
        UsernamePasswordToken usernamePasswordToken = new UsernamePasswordToken(userName, passWord);
        //获取主体对象
        Subject currentUser = SecurityUtils.getSubject();
        try {
            //登录（执行认证过程）
            currentUser.login(usernamePasswordToken);
            //成功后操作
            User user =  (User)currentUser.getPrincipal();
            //生成token
            //String token = UUID.randomUUID().toString();
            String token = userName+System.currentTimeMillis();
            //放入redis
            redisTemplate.opsForValue().set(token,user,30, TimeUnit.HOURS);
            return new Result(ReturnCode.SUCCESSS.getCode(),
                    ReturnCode.SUCCESSS.getMsg(),token);
        }  catch (AuthenticationException e) {
            e.printStackTrace();
        }
        return new Result(ExceptionConstant.ERROR_USERNAME_PASSWORD.getErrorCode(),
                ExceptionConstant.ERROR_USERNAME_PASSWORD.getErrorMessage(),null);
    }

    @Override
    public boolean checkToken(String accessToken) {
        //判断是否有key
        //Boolean hasKey = redisTemplate.hasKey(token);
        return redisTemplate.hasKey(accessToken);
        //正确
        /*if(hasKey){
          return  new Result(ReturnCode.SUCCESSS.getCode(),
                    ReturnCode.SUCCESSS.getMsg(),null);
        }
        return new Result(ReturnCode.FAIL.getCode(),
                ReturnCode.FAIL.getMsg(),null);*/
    }
}
